package com.gary.vueblog.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.gary.vueblog.entity.MBlog;
import com.gary.vueblog.entity.ResultInfo;
import com.gary.vueblog.service.MBlogService;
import com.gary.vueblog.shiro.AccountProfile;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * (MBlog)表控制层
 *
 * @author makejava
 * @since 2020-12-08 10:17:22
 */
@RestController
public class MBlogController {
    /**
     * 服务对象
     */
    @Resource
    private MBlogService mBlogService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequiresAuthentication
    @GetMapping("/selectOne")
    public ResultInfo selectOne(Long id) {
        MBlog mBlog = this.mBlogService.queryById(id);
        return ResultInfo.success( mBlog);
    }

    /**
     *  分页查询
     * @param currentPage
     * @return
     */
    @GetMapping("/blogs")
    public ResultInfo blogList(@RequestParam(defaultValue = "1") Integer currentPage) {
        //查询起始行
        Integer offset = (currentPage - 1) * 5;
        List<MBlog> mBlogs = mBlogService.queryAllByLimit(offset, 5);
        Integer count = mBlogService.queryAllCount();
        Map<Object, Object> blogBuild = MapUtil.builder()
                .put("count", count)
                .put("current", currentPage)
                .put("blogs", mBlogs)
                .build();
        return ResultInfo.success(blogBuild);
    }

    /**
     *  编辑功能 需要开启权限认证
     * @param blog
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public ResultInfo edit(@Validated @RequestBody MBlog blog) {

        AccountProfile AccountProfile = (AccountProfile)SecurityUtils.getSubject().getPrincipal();;
        MBlog temp = null;
        Assert.notNull(blog, "edit方法入参错误");
        //若 blogId 不为空 表示这是一个修改动作
        if (blog.getId() != null) {
            temp = mBlogService.queryById(blog.getId());
            //断言是否是当前登录者的博客
            Assert.isTrue(temp.getUserId().equals(AccountProfile.getId()), "您无权限编辑");
            BeanUtil.copyProperties(blog,temp,"id", "userId", "created", "status");
            mBlogService.update(temp);
        } else {
            temp = new MBlog();
            temp.setCreated(LocalDateTime.now());
            temp.setUserId(AccountProfile.getId());
            temp.setStatus(1);
            BeanUtil.copyProperties(blog,temp,"id", "userId", "created", "status");
            mBlogService.insert(temp);
        }

        return ResultInfo.success(temp);
    }

}